/***
 * Excerpted from "Stripes: and Java Web Development is Fun Again",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/fdstr for more book information.
***/
package stripesbook.action;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.SimpleError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidationErrors;
import net.sourceforge.stripes.validation.ValidationMethod;
import stripesbook.action.user.folders.MessageListActionBean;
import stripesbook.model.User;
import stripesbook.nonext.PasswordTypeConverter;

public class LoginActionBean extends BaseActionBean {
    private User user;

    @DefaultHandler
    @DontValidate
    public void view() {
    }
    @Override
    public Object getView() {
      return tag(LoginView.class);
    }
    public Resolution login() {
        getContext().setUser(user);
        if (loginUrl != null) {
            return new RedirectResolution(loginUrl);
        }
        return new RedirectResolution(MessageListActionBean.class);
    }
    public String loginUrl;

    @Validate(required=true)
    private String username;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    @Validate(required=true, converter=PasswordTypeConverter.class)
    private String password;
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @ValidationMethod
    public void validateUser(ValidationErrors errors) {
        user = userDao.findByUsername(username);
        if (user == null) {
            errors.add("username",
                new SimpleError(bundle.get("primaryEmailNotFound")));
        }
        else if (!user.getPassword().equals(password)) {
            errors.add("password",
                new SimpleError(bundle.get("passwordIncorrect")));
        }
    }
}
